<script setup>
import { ref, watch, onMounted, onBeforeUnmount, computed } from "vue";
import { useUserStore } from "@/store/modules/user";
import { likeVideoApi, unlikeVideoApi } from "@/api/like";
import { followUserApi, unfollowUserApi } from "@/api/follow";
import { createHistoryApi } from "@/api/history"; 
import { debounce } from "@/utils/index";

import VideoPlayer from "@/components/VideoPlayer/VideoPlayer.vue";
import VideoInfo from "@/components/VideoPlayer/VideoInfo.vue";
import SvgIcon from "@/components/SvgIcon/index.vue";
import UserInfoAndCommentPanel from "@/components/UserInfoAndCommentPanel/index.vue";
import CollectionModal from "@/components/CollectionModal/index.vue";

// 添加历史记录标志位
const historyRecorded = ref(false);

const props = defineProps({
  show: {
    type: Boolean,
    default: false,
  },
  video: {
    type: Object,
    default: () => ({}),
  },
});

const emit = defineEmits(["close", "fullscreen", "details"]);

const userStore = useUserStore(); // 获取用户store实例
const videoPlayerRef = ref(null);
const isPictureInPicture = ref(false);
const videoFit = ref("contain");
const showUserInfoAndCommentPanel = ref(false); // 控制评论面板显示状态
const showCollectionModal = ref(false); // 控制收藏面板显示状态
const currentVideoId = ref(null);
const currentVideo = ref(null);

// 监听视频变化，更新当前视频引用
watch(
  () => props.video,
  async (newVideo) => {
    if (newVideo) {
      currentVideo.value = { ...newVideo };
      currentVideoId.value = newVideo.id;
      
      // 当视频打开时记录历史
      if (props.show && !historyRecorded.value) {
        try {
          await recordVideoHistory(newVideo.id);
        } catch (error) {
          console.error('记录历史失败:', error);
        }
      }
    }
  },
  { immediate: true, deep: true }
);

// 监听模态框显示状态，当显示时记录历史
watch(
  () => props.show,
  async (isShown) => {
    if (isShown && currentVideoId.value && !historyRecorded.value) {
      try {
        await recordVideoHistory(currentVideoId.value);
      } catch (error) {
        console.error('记录历史失败:', error);
      }
    } else if (!isShown) {
      // 模态框关闭时重置历史记录标志
      historyRecorded.value = false;
    }
  }
);

// 记录视频历史的方法
const recordVideoHistory = async (videoId) => {
  if (!videoId || historyRecorded.value) return;
  
  try {
    await createHistoryApi(videoId);
    console.log(`已记录视频 ${videoId} 的浏览历史`);
    historyRecorded.value = true;
  } catch (error) {
    console.error('记录浏览历史失败:', error);
    throw error; // 抛出错误以便上层处理
  }
};

// 关闭模态窗
const closeModal = () => {
  // 如果正在画中画模式，先退出
  if (document.pictureInPictureElement) {
    document.exitPictureInPicture();
  }
  showUserInfoAndCommentPanel.value = false; // 关闭评论面板
  showCollectionModal.value = false; // 关闭收藏面板

// 模态框关闭时重置历史记录标志，为下次打开做准备
historyRecorded.value = false;

  // 通知父组件状态更新
  emit("updateVideo", currentVideo.value);
  emit("close");
};

// 切换画中画模式
const togglePictureInPicture = async () => {
  try {
    const videoElement = document.querySelector(".video-modal video");

    if (!videoElement) return;

    if (document.pictureInPictureElement) {
      await document.exitPictureInPicture();
      isPictureInPicture.value = false;
    } else {
      await videoElement.requestPictureInPicture();
      isPictureInPicture.value = true;
    }
  } catch (error) {
    console.error("画中画模式切换失败:", error);
  }
};

// 进入全屏模式
const enterFullscreen = () => {
  emit("fullscreen");
};

// 跳转到详情页
const goToDetails = () => {
  emit("details", currentVideoId.value);
};

// 监听画中画状态变化
const handlePictureInPictureChange = (event) => {
  isPictureInPicture.value = !!document.pictureInPictureElement;
};

// 点赞处理函数修改 - 使用防抖
const handleLike = debounce(async () => {
  if (!currentVideo.value) return;

  // 记录之前的状态以便回滚
  const previousLikeState = currentVideo.value.isLiked;
  const previousLikeCount = currentVideo.value.likeCount;

  try {
    // 先更新本地状态，让用户立即看到反馈
    currentVideo.value.isLiked = !previousLikeState;
    currentVideo.value.likeCount += currentVideo.value.isLiked ? 1 : -1;

    // 调用相应的API
    if (currentVideo.value.isLiked) {
      await likeVideoApi(currentVideoId.value);
    } else {
      await unlikeVideoApi(currentVideoId.value);
    }
    
    // 向父组件通知视频状态更新
    emit("updateVideo", currentVideo.value);
  } catch (error) {
    // 发生错误时恢复原状态
    console.error("点赞操作失败:", error);
    currentVideo.value.isLiked = previousLikeState;
    currentVideo.value.likeCount = previousLikeCount;
  }
}, 300);

// 打开评论面板
const handleComment = () => {
  showUserInfoAndCommentPanel.value = !showUserInfoAndCommentPanel.value;
  showCollectionModal.value = false; // 确保收藏面板关闭
};

// 打开收藏面板
const handleFavorites = () => {
  // 阻止事件冒泡，防止触发视频模态框的关闭
  showCollectionModal.value = true;
  showUserInfoAndCommentPanel.value = false; // 确保评论面板关闭
  currentVideo.value.favoritesCount += 1; // 模拟收藏数增加
};

// 处理收藏操作 - 添加更新事件
const handleCollect = async (selectedCollections) => {
  if (!currentVideoId.value || selectedCollections.length === 0) return;

  try {
    console.log(
      `视频${currentVideoId.value}已添加到收藏夹:`,
      selectedCollections
    );

    // 更新视频的收藏状态
    currentVideo.value.isFavorited = true;
    
    // 向父组件通知视频状态更新
    emit("updateVideo", currentVideo.value);

    // 这里可以添加成功提示
    ElMessage && ElMessage.success("收藏成功");
  } catch (error) {
    console.error("处理收藏结果失败:", error);
  } finally {
    showCollectionModal.value = false;
  }
};

// 关注用户处理函数 - 使用防抖
const handleFollow = debounce(async () => {
  if (!currentVideo.value || !currentVideo.value.user) return;

  const userId = currentVideo.value.user.id;
  const userName = currentVideo.value.user.username;
  const previousFollowState = currentVideo.value.isFollowed;

  try {
    // 调用相应的API
    if (!previousFollowState) {
      // 之前未关注，现在要关注
      const currentUserId = userStore.userInfo.id;
      await followUserApi(currentUserId, userId);
      ElMessage && ElMessage.success(`已关注 ${userName}`);
    } else {
      // 之前已关注，现在要取消关注
      const currentUserId = userStore.userInfo.id;
      await unfollowUserApi(currentUserId, userId);
      ElMessage && ElMessage.success(`已取消关注 ${userName}`);
    }

    // 更新关注状态
    currentVideo.value.isFollowed = !previousFollowState;
    // 向父组件通知视频状态更新
    emit("updateVideo", currentVideo.value);
  } catch (error) {
    if (error.message === "不能关注自己") {
      ElMessage && ElMessage.warning("不能关注自己");
    } else {
      console.error("关注操作失败:", error);
      ElMessage && ElMessage.error("操作失败，请稍后重试");
    }
  }
}, 300);

// 关闭评论面板
const closeUserInfoAndCommentPanel = () => {
  showUserInfoAndCommentPanel.value = false;
};

// 监听视频播放器的 fit 属性变化
const handleFitChange = (newFit) => {
  videoFit.value = newFit;
};

// 监听键盘事件，ESC关闭模态窗
const handleKeyDown = (event) => {
  if (event.key === "Escape" && props.show) {
    if (showUserInfoAndCommentPanel.value) {
      // 如果评论面板打开，先关闭评论面板
      showUserInfoAndCommentPanel.value = false;
    } else if (showCollectionModal.value) {
      // 如果收藏面板打开，先关闭收藏面板
      showCollectionModal.value = false;
    } else {
      closeModal();
    }
  }
};

// 添加评论数更新处理函数
const handleCommentUpdate = (count) => {
  if (!currentVideo.value) return;
  
  // 增加评论数量
  currentVideo.value.commentCount = (currentVideo.value.commentCount || 0) + count;
  
  // 向父组件通知视频状态更新
  emit("updateVideo", currentVideo.value);
};

// 组件挂载时添加事件监听
onMounted(() => {
  document.addEventListener(
    "enterpictureinpicture",
    handlePictureInPictureChange
  );
  document.addEventListener(
    "leavepictureinpicture",
    handlePictureInPictureChange
  );
  document.addEventListener("keydown", handleKeyDown);
});

// 组件卸载前移除事件监听
onBeforeUnmount(() => {
  document.removeEventListener(
    "enterpictureinpicture",
    handlePictureInPictureChange
  );
  document.removeEventListener(
    "leavepictureinpicture",
    handlePictureInPictureChange
  );
  document.removeEventListener("keydown", handleKeyDown);
});
</script>

<template>
  <div class="video-modal-container" v-if="show">
    <div class="video-modal-overlay" @click="closeModal"></div>
    <div
      class="video-modal"
      :class="{ 'with-comment-panel': showUserInfoAndCommentPanel }"
    >
      <div class="modal-header">
        <h3>{{ currentVideo?.title }}</h3>
        <div class="modal-controls">
          <!-- <button class="control-button" @click.stop="togglePictureInPicture">
            <SvgIcon :icon-class="isPictureInPicture ? 'exit-pip' : 'pip'" :size="24" />
          </button> -->
          <button class="control-button" @click.stop="enterFullscreen">
            <SvgIcon icon-class="fullscreen" :size="24" />
          </button>
          <!-- <button class="control-button" @click.stop="goToDetails">
            <SvgIcon icon-class="details" :size="24" />
          </button> -->
          <button class="control-button close" @click.stop="closeModal">
            <SvgIcon icon-class="close" :size="24" />
          </button>
        </div>
      </div>

      <div class="modal-content">
        <div
          class="video-container"
          :class="{ shrink: showUserInfoAndCommentPanel }"
        >
          <VideoPlayer
            ref="videoPlayerRef"
            :src="currentVideo?.src || ''"
            :poster="currentVideo?.coverUrl || ''"
            :autoplay="true"
            :muted="false"
            :loop="true"
            :controls="true"
            :is-active="true"
            :fit="videoFit"
            @update:fit="handleFitChange"
          >
            <VideoInfo
              :author="currentVideo?.user || {}"
              :description="currentVideo?.description || ''"
              :like-count="currentVideo?.likeCount || 0"
              :comment-count="currentVideo?.commentCount || 0"
              :favorites-count="currentVideo?.favoritesCount || 0"
              :is-like="currentVideo?.isLiked || false"
              :is-favorited="currentVideo?.isFavorited || false"
              :is-followed="currentVideo?.isFollowed || false"
              @like="handleLike"
              @comment="handleComment"
              @favorites="handleFavorites"
              @follow="handleFollow"
            />
          </VideoPlayer>
        </div>

        <!-- 评论面板 -->
        <UserInfoAndCommentPanel
          :show="showUserInfoAndCommentPanel"
          :video-id="currentVideoId"
          :video="currentVideo"
          @close="closeUserInfoAndCommentPanel"
          @follow="handleFollow"
          @commentUpdate="handleCommentUpdate"
        />
      </div>
    </div>
    <!-- 收藏弹窗 -->
    <CollectionModal
      :show="showCollectionModal"
      :video-id="currentVideoId"
      @close="showCollectionModal = false"
      @collect="handleCollect"
    />
  </div>
</template>

<style scoped lang="scss">
.video-modal-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1001;
  display: flex;
  justify-content: center;
  align-items: center;
}

.video-modal-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.7);
  z-index: 1001;
}

.video-modal {
  position: relative;
  width: 100%;
  height: 100%;
  background-color: #000;
  border-radius: 8px;
  overflow: hidden;
  z-index: 1002;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
  display: flex;
  flex-direction: column;

  @media (max-width: 768px) {
    width: 100%;
    height: 100%;
    border-radius: 0;
  }

  // 添加评论面板显示时的样式
  &.with-comment-panel {
    .modal-content {
      display: flex;
      flex-direction: row;

      @media (max-width: 767px) {
        flex-direction: column;
      }
    }
  }
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background-color: rgba(0, 0, 0, 0.8);
  color: white;

  h3 {
    margin: 0;
    font-size: 16px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .modal-controls {
    display: flex;
    gap: 8px;

    .control-button {
      background: none;
      border: none;
      color: white;
      cursor: pointer;
      width: 32px;
      height: 32px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      transition: background-color 0.2s;

      &:hover {
        background-color: rgba(255, 255, 255, 0.2);
      }

      &.close:hover {
        background-color: rgba(255, 0, 0, 0.3);
      }
    }
  }
}

.modal-content {
  flex: 1;
  position: relative;
  overflow: hidden;
  display: flex;
  flex-direction: column;

  @media (min-width: 768px) {
    flex-direction: row;
  }
}

.video-container {
  flex: 1;
  position: relative;
  overflow: hidden;
  transition: all 0.3s ease;
  width: 100%;
  height: 100%;

  @media (min-width: 768px) {
    &.shrink {
      width: calc(100% - 400px);
    }
  }

  @media (max-width: 767px) {
    &.shrink {
      height: 40%;
    }
  }
}
</style>
